import React from 'react';
import { useEffect, useState } from 'react';
import { Navigate, NavLink, useRoutes } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { Button, Form, Input, message, Select, Space } from 'antd';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import ButtonGroup from '../../components/ButtonGroup/ButtonGroup.jsx';
import DataTable from '../../components/DataTable/DataTable.jsx';
import http from '../../api/index.js';
import { getColorEnumColor } from '../../enums/index.js';
import { createUserStore } from '../../store/index.js';
import './List.css';

/**
 * 列表页
 * @returns
 */
function List(props) {
  console.log(props);

  const { userInfo, SexEnum } = props;

  const navigate = useNavigate();

  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);

  const [sex, setSex] = useState('');
  const [loading, setLoading] = useState(false);

  const params = {
    sex: '',
    currentPage: 1,
    pageSize: 5,
  };

  // 初始化数据
  async function getListData() {
    setLoading(true);

    const res = await http.get('/getUserList', {
      params: params,
    });

    setList(
      res.records.map((item) => {
        item.key = item.id;
        item.colorName = getColorEnumColor(item.color);
        item.onRefresh = () => {
          getListData();
        };
        return item;
      }),
    );

    setTotal(res.total);
    setLoading(false);
  }

  function handleSexChange(e) {
    params.sex = e.target.value;

    setSex(params.sex);

    getListData();
  }

  const onClick = () => {
    navigate('/add');
  };

  const onChange = (pagination, filters, sorter, extra) => {
    // paginate | sort | filter
    console.log(pagination, extra);
    if (extra.action == 'paginate') {
      params.currentPage = pagination.current;
      getListData();
    }
  };

  // 初始化
  async function initData() {
    await getListData();
  }

  useEffect(() => {
    initData();
  }, []);

  return (
    <>
      <div className="flex justify-between items-center">
        <div>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={onClick}>
              添加
            </Button>

            <ButtonGroup value={sex} onChange={handleSexChange}></ButtonGroup>
          </Space>
        </div>

        <div>{userInfo?.name}</div>
      </div>

      <DataTable
        className="mt-md"
        loading={loading}
        dataSource={list}
        onChange={onChange}
        pagination={{
          position: ['bottomCenter'],
          defaultCurrent: params.currentPage,
          defaultPageSize: params.pageSize,
          total: total,
        }}
      ></DataTable>
    </>
  );
}

export default createUserStore(List);
